package me.seu.demo.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.controller.req.UpdateRuleReq;
import me.seu.demo.service.AccessLimitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @since 2020/4/16 14:51
 */
@Slf4j
@RestController
@RequestMapping("/limit")
public class LimitController {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private AccessLimitService accessLimitService;

    @GetMapping("/access")
    public String access() {
        //尝试获取令牌
        if (accessLimitService.tryAcquire()) {
            //模拟业务执行500毫秒
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "access success [" + sdf.format(new Date()) + "]";
        } else {
            return "access limited [" + sdf.format(new Date()) + "]";
        }
    }

    @GetMapping("/str")
    public String limitAccess() {
        log.info("[limitAccess] limit str = {}", accessLimitService.limitStr);
        log.info("[limitAccess] limit str get method = {}", accessLimitService.getLimitStr());
        return accessLimitService.limitStr;
    }

    /**
     * 编辑规则
     *
     * @param req
     */
    @PostMapping(value = "/rule/update")
    public void editRule(@RequestBody UpdateRuleReq req) {
        log.info("[editRule] params={}", JSONObject.toJSONString(req));
    }

}
